<?php

namespace app\admin\controller;

use app\admin\service\AccountService;
use app\admin\service\CommonService;
use app\admin\service\StudentService;
use app\admin\validate\StudentValidate;
use app\models\CampusModel;
use app\models\ContractModel;
use app\models\CourseContractModel;
use app\models\CourseModel;
use app\models\DictionaryModel;
use app\models\FollowUpLogModel;
use app\models\GoodsContractModel;
use app\models\GoodsModel;
use app\models\GradesContractModel;
use app\models\GradesDetailsModel;
use app\models\GradesModel;
use app\models\MarkingModel;
use app\models\ParentInformationModel;
use app\models\PayFlowModel;
use app\models\ReceivablesModel;
use app\models\StudentModel;
use app\models\UserModel;

class Student extends Common
{

    /**
     * 资金流水.
     *
     *  @var PayFlowModel
     */
    protected $payFlowModel;

    /**
     * 物品与合同管理模型.
     *
     *  @var GoodsContractModel
     */
    protected $goodsContractModel;

    /**
     * 班级与合同管理模型.
     *
     *  @var GradesContractModel
     */
    protected $gradesContractModel;

    /**
     * 校区管理模型.
     *
     * @var CampusModel
     */
    protected $campusModel;
    /**
     * 班级管理详情模型.
     *
     * @var GradesDetailsModel
     */
    protected $gradesdetailModel;

    /**
     * 批阅模型.
     *
     * @var MarkingModel
     */
    protected $markingModel;

    /**
     * 学员模型.
     *
     * @var StudentModel
     */
    protected $studentModel;

	/**
	 * 收款管理模型.
	 *
	 * @var ReceivablesModel
	 */
	protected $receivablesModel;

    /**
     * 用户模型.
     *
     * @var UserModel
     */
    protected $userModel;

	/**
	 * 班级模型.
	 *
	 * @var GradesModel
	 */
	protected $gradesModel;

    /**
     * ContractModel 订单模型.
     *
     * @var ContractModel
     */
    protected $contractModel;
	/**
	 * 学员课程订单关系模型
	 * @var CourseContractModel
	 */
    protected $courseContractModel;

    /**
     * 跟进沟通记录模型.
     *
     * @var FollowUpLogModel
     */
    protected $followUpLogModel;

    /**
     * 验证.
     *
     * @var StudentValidate
     */
    protected $studentValidate;

    /**
     * 学员管理.
     *
     * @throws \think\Exception
     * @throws \think\exception\DbException
     *
     * @return mixed
     */
    public function lists()
    {
        if ($this->request->isAjax())
        {
            $param = $this->request->param();
        	if(input('p') == 1){
        		$this->getStudentSingUpLists();
        		return;
			}

            $param['is_audition'] = 2;
            $course = $this->studentModel->getStudentLists($param);

            $this->success('success', '', $course, 0);
        }
        $where = [];
        $where_campus = [];
        $where['status'] =  1; //未禁用
        $where_campus['status'] = 1;
		if(get_current_type() == 4 || get_current_type() == 5){
			$where['campus_id'] = get_current_campus_id();
            $where_campus['id'] = get_current_campus_id();
		}elseif (get_current_type() == 2 || get_current_type() == 3){
			$where['campus_id'] = ['in',get_current_campus_id()];
            $where_campus['id'] = ['in',get_current_campus_id()];
		}

        /********选择校区******/
        $campus = $this->campusModel->where($where_campus)->select();

        /********班级*****/
        $grades_class = $this->gradesdetailModel->where($where)->select();
        /******班主任****/
        if(get_current_type() == 1){
            $headmaster = $this->userModel->where([ 'group_type' => 4])->select();
        }else{
            $headmaster = $this->userModel->where(['campus_id' => $where['campus_id'], 'group_type' => 4])->select();
        }


		$where['status'] = 1;
        $users = $this->userModel->where($where)->field('id,name')->select()->toArray();
        $arr[] = [
            'id' => 0,
            'name' => '公海',
        ];
        $users = array_merge($users, $arr);
        $this->dictionary();




        return $this->fetch('', [
            'users' => $users,
            'grades_class' => $grades_class,
            'headmaster' => $headmaster,
            'campus' => $campus,
        ]);
    }

    public function studentlists()
	{
        if ($this->request->isAjax()) {
            $param = $this->request->param();
            $param['is_audition'] = 2;
            $course = $this->studentModel->getStudentLists($param);

            $this->success('success', '', $course, 0);
        }
    }

	private function getStudentSingUpLists()
	{
		if ($this->request->isAjax()) {
			$param = $this->request->param();
			$course = $this->studentModel->getStudentSingUpLists($param);
			$this->success('success', '', $course, 0);
		}
	}

    /**
     * 批阅.
     */
    public function marking()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $_data = input('post.');
            $data['lid'] = $_data['id']; // 跟进记录id
            $data['marking'] = $_data['marking']; // 批阅内容
            $data['time'] = date('Y-m-d H:i:s'); // 批阅时间
            $data['name'] = get_current_name(); // 操作人ID
            $data['img'] = get_current_avatar(); // 操作人头像
            $marking = $this->markingModel->save($data);
            if (false !== $marking) {
                $this->success('添加成功', '', $data, 1);
            }
            $this->error('添加失败', null, '', 1);
        }
    }

    /**
     * 学员信息.
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     * @return \think\response\Json|\think\response\View
     */
    public function information()
    {
        $student = StudentModel::get(input('id'));
        $student['register_date'] = substr($student['register_date'], 0, 11);
        $student['follow_up_text'] = DictionaryModel::getById($student['follow_up'], 'name');
        if ($student['channel'] > 0) {
            $student['channel'] = DictionaryModel::getById($student['channel'], 'name');
        } elseif (-1 === $student['channel']) {
            $student['channel'] = '转介绍';
        } else {
            $student['channel'] = '--';
        }

		//学费余额
		$student['balance'] = ($this->contractModel->where(['student_id'=>$student['id']])->sum('balance')) / 100;
        //介绍人
        $student['introduction'] = $this->studentModel->where(['introduction'=>$student['id']])->value('student_name');
        $followUpLog = $this->followUpLogModel->where(['student_id' => input('id')])->order('timestamp desc')->find();
        $student['date'] = $followUpLog['date'];
        $student['time'] = $followUpLog['time'];
        $logs = $this->followUpLogModel->where(['student_id' => input('id')])->order('timestamp desc')->select()->toArray();
        foreach ($logs as &$log) {
			if (2 === (int) $log['type']) {
				$log['type_text'] = get_current_name();
				$log['avatar'] = get_current_avatar();
			}else{
				$log['type_text'] = '系统';
				$log['avatar'] = '/favicon.ico';
			}
            $log['follow_up'] = DictionaryModel::getById($log['follow_up'], 'name');
            $log['mode'] = DictionaryModel::getById($log['mode'], 'name');
            if ($log['intentional_grade'] < 3) {
                $log['intentional_grade_text'] = '低';
            } elseif ($log['intentional_grade'] > 3) {
                $log['intentional_grade_text'] = '高';
            } else {
                $log['intentional_grade_text'] = '中';
            }
            $log['marks'] = $this->markingModel->where(['lid' => $log['id']])->select();
        }

        /**订单记录**/
        $Order_json = [];   //返回前台订单json
        $Flow_json = [];   //返回前台流水json
        $Stored_json = [];   //返回前台储值json
        $res = $this->contractModel->where(['student_id' => input('id')])->order('signing_date asc')->select();
        foreach ($res as $value){
            $Order_json_item = [];
            $Flow_json_item = [];
            $Stored_json_item = [];
            /*********直接报名************/
            //课程
            $res_course = $this->courseContractModel->where(['contract_id' => $value['id'],  'student_id' => input('id')])->select();
            foreach ($res_course as $value_course){
                $item_Order = [];
                $course_result = CourseModel::get(['id' => $value_course['course_id']]);
                $item_Order['project_name'] = $course_result['course_name']; //项目
                $item_Order['project_price'] = ($value_course['price']/100).'/'.$course_result['unit'];  //单价
                $item_Order['project_nums'] = $value_course['class_num'].'/'.$course_result['unit'];  //数量
                $item_Order['project_discount'] = ($value_course['direct_money'] + $value_course['assessed_amount'])/100; //优惠金额[直减 + 分摊];
                $item_Order['project_give_nums'] = $value_course['give_class_num'];  //赠送
                $item_Order['project_net_receipts'] = ($value_course['net_receipts'] - $value_course['assessed_amount'])/100; //应收
                $item_Order['project_actual'] = $value_course['payment'] / 100;  //实收
                $item_Order['project_arrears'] = ($item_Order['project_net_receipts'] - $item_Order['project_actual']);  //欠费
                $Order_json_item[] = $item_Order;
            }

            //班级
            $res_grades = $this->gradesContractModel->where(['contract_id' => $value['id'], 'student_id' => input('id')])->select();
            foreach ($res_grades as $value_grades){
                $item_Order = [];
                $grades_result = GradesDetailsModel::get(['id' => $value_grades['grades_id']]);
                $course_result = CourseModel::get(['id' => $value_grades['course_id']]);
                $item_Order['project_name'] = $grades_result['grades_name']; //项目
                $item_Order['project_price'] = ($value_grades['price']/100).'/'.$course_result['unit'];  //单价
                $item_Order['project_nums'] = $value_grades['class_num'].'/'.$course_result['unit'];  //数量
                $item_Order['project_discount'] = ($value_grades['direct_money'] + $value_grades['assessed_amount'])/100; //优惠金额[直减 + 分摊];
                $item_Order['project_give_nums'] = $value_grades['give_class_num'];  //赠送
                $item_Order['project_net_receipts'] = ($value_grades['net_receipts'] - $value_grades['assessed_amount'])/100; //应收
                $item_Order['project_actual'] = $value_grades['payment'] / 100;  //实收
                $item_Order['project_arrears'] = ($item_Order['project_net_receipts'] - $item_Order['project_actual']);  //欠费
                $Order_json_item[] = $item_Order;
            }

            //物品
            $res_goods = $this->goodsContractModel->where(['contract_id' => $value['id'], 'student_id' => input('id')])->select();
            foreach ($res_goods as $value_goods){
                $item_Order = [];
                $goods_result = GoodsModel::get(['id' => $value_goods['goods_id']]);
                $item_Order['project_name'] = $goods_result['goods_name']; //项目
                $item_Order['project_price'] = ($value_goods['price']/100).'/'.$goods_result['unit'];  //单价
                $item_Order['project_nums'] = $value_goods['goods_num'].'/'.$goods_result['unit'];  //数量
                $item_Order['project_discount'] = ($value_goods['direct_money'] + $value_goods['assessed_amount'])/100; //优惠金额[直减 + 分摊];
                $item_Order['project_give_nums'] = '-';  //赠送
                $item_Order['project_net_receipts'] = ($value_goods['net_receipts'] - $value_goods['assessed_amount'])/100; //应收
                $item_Order['project_actual'] = $value_goods['payment'] / 100;  //实收
                $item_Order['project_arrears'] = ($item_Order['project_net_receipts'] - $item_Order['project_actual']);  //欠费
                $Order_json_item[] = $item_Order;
            }
            /*************流水***************/
            $res_receivables = $this->payFlowModel->where(['contract_number' => $value['contract_number']])->select();
            foreach($res_receivables as $value_flowmodel){
                $item_Flow = [];
                $item_Flow['flow_number'] = $value_flowmodel['receipt_number'];  //流水号
                $item_Flow['flow_time'] = $value_flowmodel['create_time'];  //收款日期
                $item_Flow['flow_payment_method'] =DictionaryModel::get($value_flowmodel['pay_channel'])['name']; //支付方式
                $item_Flow['flow_amount'] = $value_flowmodel['amount']/100; //金额
                if($value_flowmodel['type'] == 1){
                    $item_Flow['flow_type'] = '订单收入';
                }else if($value_flowmodel['type'] == 2){
                    $item_Flow['flow_type'] = '订单退费';
                }
                $item_Flow['flow_remark'] = $value_flowmodel['remark']; //备注
                $Flow_json_item[] = $item_Flow;
            }

            /****************储值*****************/
            $item_Stored = [];
            $item_Stored['store_total_receipts'] =   ContractModel::where(['student_id' => input('id')])->sum('storedvalue') /100; //总额
            $item_Stored['store_net_receipts'] = $value['storedvalue']/100;  //本次储值金额
            $item_Stored['store_surplus_money'] = StudentModel::get(['id' => input('id')])['storedvalue'];
            $item_Stored['store_surplus_money'] = $item_Stored['store_surplus_money'] /100; //储值剩余总额
            $Stored_json_item[] = $item_Stored;

            $Order_json_item_ = [];
            $Order_json_item_['contract_number'] = $value['contract_number']; //订单号
            $Order_json_item_['signing_date'] = $value['create_time']; //签约日期
            $Order_json_item_['order_json'] = $Order_json_item; //订单详情
            $Order_json[] = $Order_json_item_;

            $Flow_json_item_ = [];
            $Flow_json_item_['contract_number'] = $value['contract_number']; //订单号
            $Flow_json_item_['signing_date'] = $value['create_time']; //签约日期
            $Flow_json_item_['flow_json'] = $Flow_json_item; //流水详情
            $Flow_json[] = $Flow_json_item_;

            $Stored_json_item_ = [];
            $Stored_json_item_['contract_number'] = $value['contract_number']; //订单号
            $Stored_json_item_['signing_date'] = $value['create_time']; //签约日期
            $Stored_json_item_['stored_json'] = $Stored_json_item; //储值详情
            $Stored_json[] = $Stored_json_item_;
        }

        $Order_json = json_encode($Order_json);  //报名订单
        $Flow_json = json_encode($Flow_json);  //流水订单
        $Stored_json = json_encode($Stored_json); ;  //储值订单
        $this->dictionary();

		return $this->fetch('', ['Stored_json' => $Stored_json, 'Flow_json' => $Flow_json, 'Order_json' => $Order_json,'student' => $student, 'logs' => $logs, 'date' => date('Y-m-d')]);
    }

	/**
	 * 就读班级
	 * modify by Small Y
	 *
	 * @return mixed
	 * @throws \think\exception\DbException
	 */
    public function attending_classes()
	{
		if ($this->request->isAjax()) {
			$param = $this->request->param();
			$param['graduation_status'] = 0;
			$attending_classes = $this->studentModel->getClass($param);

			$this->success('success', '', $attending_classes, 0);
		}
		return $this->fetch();
	}

	/**
	 * 过往班级
	 * modify by Small Y
	 *
	 * @return mixed
	 * @throws \think\exception\DbException
	 */
	public function past_class()
	{
		if ($this->request->isAjax()) {
			$param = $this->request->param();
			$param['graduation_status'] = 1;
			$past_class = $this->studentModel->getClass($param);

			$this->success('success', '', $past_class, 0);
		}
		return $this->fetch();
	}

	/**
	 * 直接报名
	 * modify by Small Y
	 *
	 * @return mixed
	 * @throws \think\exception\DbException
	 */
	public function direct_enrolment()
	{
		if ($this->request->isAjax()) {
			$param = $this->request->param();
			$param['is_audition'] = 2;
			$past_class = $this->courseContractModel->getDirectEnrolment($param);

			/*
			$past_class = $this->contractModel->getOrderRecordList($param);
			*/

			$this->success('success', '', $past_class, 0);
		}
		return $this->fetch();
	}

	/**
	 * 账户充值
	 * modify by Small Y
	 *
	 * @return mixed
	 * @throws \think\exception\DbException
	 */
	public function account_recharge()
	{
		if ($this->request->isAjax()) {
			$param = $this->request->param();
			$past_class = $this->receivablesModel->getAccountRecharge($param);

			$this->success('success', '', $past_class, 0);
		}
		return $this->fetch();
	}

    /**
     * 添加跟进记录.
     *
     * @throws \think\exception\DbException
     */
    public function addFollowUp()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            $data['timestamp'] = time(); // 跟进记录时间戳
            $data['time'] = date('Y-m-d H:i:s'); // 跟进记录时间
            $data['date'] = date('Y-m-d'); // 跟进记录日期
            $data['date'] = date('Y-m-d'); // 跟进记录日期
            $data['user_id'] = get_current_id(); // 操作人ID
            $data['img'] = get_current_avatar(); // 操作人头像
            $data['type'] = 2; // 沟通记录
            $data['next_follow_up_date'] = $data['next_follow_up_date'] ? $data['next_follow_up_date'] : null; //下次跟进日期
            $followUpLog = $this->followUpLogModel->save($data);
            $_data = array(
                'next_follow_up_record'=>$data['next_follow_up_date'],//跟进日期
            );
            $this->studentModel->save($_data,['id'=>$data['student_id']]);
            $data['type_text'] = get_current_name();
            $data['avatar'] = get_current_avatar();
            $data['mode'] = DictionaryModel::getById($data['mode'], 'name');
            if (false !== $followUpLog) {
                $this->success('添加成功', '', $data, 1);
            }
            $this->error('添加失败', null, '', 1);
        }
    }

    /**
     * 添加学员.
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     * @return mixed
     */
    public function add()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $_data = input('post.');
            if (!$this->studentValidate->scene('add')->check($_data)) {
                $this->error($this->studentValidate->getError(), null, '', 1);
            }
            $data['phone'] = $_data['phone'];
            $data['campus_id'] = $_data['campus_id'];

            /*
            $data['course_consultant_type'] = $_data['course_consultant_type'];
            if ('1' === $_data['course_consultant_type']) {
                $data['course_consultant'] = get_current_name();
                $data['user_id'] = get_current_id();
            } else {
                $data['course_consultant'] = '公海';
                $data['user_id'] = 0;
            }
            */

            if($_data['user_id'] == 0){
                $data['course_consultant_type']  = 2; //公海
                $data['course_consultant'] = '公海';
                $data['user_id'] = 0;
            }else{
                $data['course_consultant_type']  = 1;
                $data['user_id'] = $_data['user_id'];
                $data['course_consultant'] = $this->userModel->get(['id' => $_data['user_id']])['name'];
            }


            $data['is_audition'] = 1;
            $data['channel'] = $_data['channel'] ? $_data['channel'] : 0;
            $data['introduction'] = $_data['introduction'];
            $data['sex'] = $_data['sex'];
            $data['remark'] = $_data['remark'];
            $data['student_name'] = $_data['name'];
            $data['name'] = $_data['name'];
            $data['student_number'] = CommonService::generateStudentNumber();  //学号
            $data['address'] = $_data['address'];
            $data['age'] = $_data['age'];
            $data['grade'] = $_data['student_grade'];
            $data['school_class'] = $_data['school_class'] ? $_data['school_class'] : '--';
            $data['father_name'] = $_data['father_name'];
            $data['father_phone'] = $_data['father_phone'];
            $data['mother_name'] = $_data['mother_name'];
            $data['guardian'] = $_data['guardian'];
            $data['guardian_phone'] = $_data['guardian_phone'];
            $data['weixin'] = $_data['weixin'];
            $data['qq'] = $_data['qq'];
            $data['mother_phone'] = $_data['mother_phone'];
            $data['birth'] = $_data['birth'] ? $_data['birth'] : null;
            $data['register_date'] = date('Y-m-d');
            $data['follow_up'] = 35;
            $student = $this->studentModel->save($data);

			//家长信息写入 开始
			$parentInformation = [];
			$parentInformation['student_id'] = $this->studentModel->id;//学员ID
			$parentInformation['campus_id'] = $_data['campus_id'];//校区ID
			$parentInformation['name'] = $_data['guardian'];//姓名
			$parentInformation['username'] = $_data['guardian_phone'];//手机号码
			$parentInformation['salt'] = md5(date('Y-m-d H:i:s'));
			$parentInformation['password'] = AccountService::encodePassword(123456, $parentInformation['salt']);//密码
			$parentInformation['img'] = '/img.jpg';//头像
			$parentInformation['status'] = 1;//状态：1启用 0禁用
			(new ParentInformationModel())->save($parentInformation);
			//家长信息写入 结束

			if (false !== $student) {
                session("student_id_session",null);
                $this->success('添加成功', '', $this->studentModel->id, 1);
            }
            $this->error('添加学员失败', null, '', 1);
        }
        $this->dictionary();
        $where = [];
		if(get_current_type() == 4 || get_current_type() == 5){
			$where['campus_id'] = get_current_campus_id();
		}elseif (get_current_type() == 2 || get_current_type() == 3){
			$where['campus_id'] = ['in',get_current_campus_id()];
		}
		$where['status'] = 1;
        $students = $this->studentModel->where($where)->select()->toArray();
        $type = input('type');
        $campus_id = input('campus_id');
        $sourse_data = input('sourse_data');

        $where_user = [];
        $where_user['status'] = 1;
        if(get_current_type() == 4 || get_current_type() == 5){/*校区员工数据权限*/
            $where_user['campus_id'] = get_current_campus_id();
        }elseif (get_current_type() == 3 || get_current_type() == 2){/*系统区域数据权限*/
            $where_user['campus_id'] = ['in',get_current_campus_id()];
        }
        if(get_current_type() == 5){
            $where_user['id'] = get_current_id();
        }
        $users = $this->userModel->where($where_user)->field('id,name')->select()->toArray();
        if(get_current_type() != 5){
            $arr[] = [
                'id' => 0,
                'name' => '公海',
            ];
            $users = array_merge($users, $arr);
        }


        return $this->fetch('', [	'users' => $users,'students' => $students,'type' => $type,'campus_id'=>$campus_id,'sourse_data' => $sourse_data]);
    }

    /**
     * 获取学员信息.
     *
     * @throws \think\exception\DbException
     *
     * @return array
     */
    public function getStudentInformation()
    {
        $student = $this->studentModel->get(['id' => input('id')]);
        $student['grade'] = CommonService::getDictionaryName($student['grade']);
        $student['grade'] = $student['grade'] ? $student['grade'] : '--';
        $student['student_name'] = $student['student_name'] ? $student['student_name'] : '--';
        $student['phone'] = $student['phone'] ? $student['phone'] : '--';
        $student['school_class'] = $student['school_class'] ? $student['school_class'] : '--';
        $channel = DictionaryModel::getById($student['channel'],'name');
        $student['channel'] = $channel ? $channel : '--';
        $student['birth'] = $student['birth'] ? $student['birth'] : '--';
        /*录入类型，如果存在该生合同则为老生，否则为新生*/
        $res = $this->contractModel->get(['student_id' => input('id')]);
        if(!$res){
            $student['input_type'] = 0;
        }else{
            $student['input_type'] = 1;
        }
        session("student_id_session",$student);

        return ['code' => 1, 'data' => $student];
    }

    /**
     * 学员修改.
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     * @return \think\response\Json|\think\response\View
     */
    public function edit()
    {
        if (request()->isPost()) {
            return json((new StudentService())->logic($type = 2));
        }
        $status_infos = input('status_infos'); //是否开班
        $type = input('type');
        $student = StudentModel::get(input('id'));
        $campus_name = CampusModel::get(['id' => $student['campus_id']])['campus_name'];
        $this->dictionary();

		return $this->fetch('', [
			'student' => $student,
            'campus_name' => $campus_name,
            'status_infos' => $status_infos,
            'type' => $type
		]);
    }

    /**
     * 将学员转给同事.
     *
     * @throws \think\exception\DbException
     *
     * @return mixed
     */
    public function assignment()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            $where['id'] = ['in', input('ids')];
            $arr = explode(',', input('ids'));
            $data['name'] = $this->userModel->get(['id' => $data['user_id']])['name'];
			$res = $this->studentModel->save(['user_id' => $data['user_id'], 'campus_id' => input('campus_id'),  'course_consultant' => $data['name']], $where);
            foreach ($arr as $id) {
                // 学员客户跟进沟通记录写入
				$student = StudentModel::get($id);
                CommonService::writeFollowUpLog($id, input('campus_id'),1, get_current_name().' '.'将客户'.' '.$student['student_name'].' '.'转给了同事'.' '.$data['name'], 1,$student['follow_up']);
            }
            if (false === $res) {
                $this->error('操作失败', null, '', 2);
            }
            $this->success('操作成功', null, '', 1);
        }

        return $this->fetch('', [
        	'ids' => input('ids'),
        	'campus_id' => input('campus_id')
		]);
    }

    /**
     * 当前校区的所有用户.
     *
     * @throws \think\exception\DbException
     */
    public function query()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param();
            $list = $this->userModel->getLists($param);

            $this->success('success', '', $list, 0);
        }
    }

    /**
     * 移除学员.
     */
    public function delete()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $where['id'] = ['in', input('ids')];
            $res = $this->studentModel->where($where)->delete();
            if (false === $res) {
                $this->error('移除失败', null, '', 2);
            }
            $this->success('移除成功', null, '', 1);
        }
    }

    public function choice_contract(){

        $contract_id = input('contract_id');
        $contract_number_name = input('contract_number_name');

        return $this->fetch('',['contract_id' => $contract_id, 'contract_number_name' => $contract_number_name]);
    }


    /**
     * 导入学员表.
     *
     * @return mixed
     */
    public function student_excel()
    {

        try {
            if (request()->isPost()){
                $file = request()->file('file');
                if($file->getInfo()['error'] == 0){
                    $filename = $file->getInfo()['name'];

                    $file_type = explode(".",$filename)[1];
                    if(strcasecmp($file_type,"Xlsx")== 0 || strcasecmp($file_type,"Xls") == 0
                        || strcasecmp($file_type,"Xml") == 0 || strcasecmp($file_type,"Ods") == 0
                        || strcasecmp($file_type,"Slk") == 0 || strcasecmp($file_type,"Gnumeric") == 0
                        || strcasecmp($file_type,"Html") == 0 || strcasecmp($file_type,"Csv") == 0){

                        $filename = 'Import_student_excel.'.$file_type;
                        $file->move(ROOT_PATH . 'public',$filename); //上传后的文件名
                        $excelData = readExcelFile(ROOT_PATH . 'public/'.$filename); //读表
                        if ($excelData != null) {
                            if(is_file(ROOT_PATH . 'public/'.$filename) && unlink(ROOT_PATH . 'public/'.$filename)){
                                //插入数据库
                                $student_table = []; //学员表

                                foreach ($excelData as $key => $value){
                                    if(!$this->studentModel->get(['phone' => $value[1]])){
                                        $item['student_name'] = $value[0]; //学员姓名
                                        $item['phone'] = $value[1]; //电话
                                        $item['channel'] = $this->dictionaryModel->get(['type' => 2, 'name' => $value[2]])['id']; //来源渠道
                                        $res_student = $this->studentModel->get(['name' => $value[3]]);
                                        if(!$res_student){
                                            $item['introduction'] = 0;
                                        }else{
                                            $item['introduction'] = $res_student['id'];  //介绍人
                                        }
                                        $item['intentional_course'] = $value[4]; //意向课程
                                        $item['intentional_grade'] = $value[5]; //意向级别
                                        $item['course_consultant'] = $value[6]; //课程顾问
                                        $item['follow_up_object'] = $value[7]; //跟进对象
                                        if($value[8] == '男'){
                                            $item['sex'] = 1; //性别
                                        }else if($value[7] == '女'){
                                            $item['sex'] = 2; //性别
                                        }
                                        $item['remark'] = $value[9];  //备注
                                        $item['birth'] = $value[10]?$value[10]:null; //生日
                                        $item['address'] = $value[11]; //居住区域
                                        $item['age'] = $value[12]; //客户年龄
                                        $res_grades = $this->dictionaryModel->get(['type' => 1, 'name' => $value[13]]); //学员年级
                                        if(!$res_grades){
                                            $item['grade'] = 0;
                                        }else{
                                            $item['grade'] = $res_grades['id'];
                                        }
                                        $item['school_class'] = $value[14];  //学校班级
                                        $item['guardian'] = $value[15];  //监护对象
                                        $item['guardian_phone'] = $value[16];  //监护对象电话号码
                                        $item['weixin'] = $value[17];  //微信
                                        $item['qq'] = $value[18];  //QQ
                                        $item['name'] = $value[0]; //客户姓名
                                        $item['campus_id'] = get_current_campus_id(); //校区ID
                                        $item['user_id'] = get_current_id(); //当前用户ID
                                        $item['course_consultant'] = get_current_name(); //当前用户名称
                                        $item['course_consultant_type'] = 1; //当前用户类型
                                        $item['is_audition'] = 1; //类型
                                        $item['register_date'] = date('Y-m-d');; //注册日期
                                        $item['follow_up'] = 34; //未处理
                                        $item['student_number'] =  CommonService::generateStudentNumber();  //学号
                                        $item['is_audition'] = 2; //正式学员
                                        $item['sign_up'] = 0; //未报名
                                        $student_table[] = $item;
                                    }
                                }

                                if(count($student_table) > 0){
                                    $this->studentModel->saveAll($student_table);
                                    return ['code' => 0, 'data' => $excelData, 'name' => $filename, 'size'=>$file->getInfo()['size']];
                                }else{
                                    return ['code' => 0, 'name' => $filename];
                                }
                            }

                        }
                    }
                }



            }

        } catch (\Exception $e) {
            return ['code' => 1, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 实例化.
     *
     * @return bool|void
     */
    protected function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $this->studentModel = new StudentModel();
        $this->contractModel = new ContractModel();
        $this->gradesModel = new GradesModel();
        $this->userModel = new UserModel();
        $this->followUpLogModel = new FollowUpLogModel();
        $this->markingModel = new MarkingModel();
        $this->studentValidate = new StudentValidate();
        $this->receivablesModel = new ReceivablesModel();
        $this->courseContractModel = new CourseContractModel();
        $this->campusModel = new CampusModel();
        $this->gradesdetailModel = new GradesDetailsModel();
        $this->gradesContractModel = new GradesContractModel();
        $this->goodsContractModel = new GoodsContractModel();
        $this->payFlowModel = new PayFlowModel();
    }
}